package com.oocl.euc.pagination;

import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


public abstract class PaginationService<T> {
	public BaseConditionQuery<T> getQuery(Integer limit,Integer page,String searchFilters,String sort){
		BaseConditionQuery<T> query=new BaseConditionQuery<T>();
		List<SearchFilter> filters=JSON.parseArray(searchFilters, SearchFilter.class);
		JSONObject jsonSort=JSON.parseObject(sort);
		Order order=null;
		if(jsonSort!=null){
			if(Direction.DESC.toString().equalsIgnoreCase((String)jsonSort.get("direction"))){
				order=new Order(Direction.DESC, jsonSort.getString("property"));
			}else{
				order=new Order(Direction.ASC, jsonSort.getString("property"));
			}
			Sort pageSort=new Sort(order);
			query.setSort(pageSort);
		}
		query.setLimit(limit);
		query.setPage(page);
		
		SearchFilter[] pageFilters=null;
		if(filters!=null){
			pageFilters=new SearchFilter[filters.size()];
			int i=0;
			for(SearchFilter s:filters){
				if(s.fieldName.equals("createTime")){
					s.value=new Date(Long.parseLong((s.value).toString()));
				}
				pageFilters[i]=s;
				i++;
			}
		}
		query.setSearchFilters(pageFilters);
		return query;
	}
}
